package com.jet.chat.dbquery;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ChatQueryGetChannelHistory extends ChatQueryAbstract {

	@Override
	protected ChatQueryResult main(Connection conn, ChatQueryParams chatQueryParams) throws Exception {
		String channelName = ((ChatQueryGetChannelHistoryParams) chatQueryParams).getChannelName();
		String timestamp = ((ChatQueryGetChannelHistoryParams) chatQueryParams).getTimestamp();
		
		ChatQueryGetChannelHistoryResult result = new ChatQueryGetChannelHistoryResult();

		PreparedStatement ps = conn.prepareStatement("select u.username, m.timestamp, m.content from messages as m, users as u where m.channelname = ? and u.id = m.senderid and m.pub = ? and timestamp >= ?");
		ps.setString(1, channelName);
		ps.setInt(2, 1);
		ps.setString(3, timestamp);
		ResultSet results = ps.executeQuery();
		while(results.next()) {
			ChatQueryGetChannelHistoryResultRaw raw = new ChatQueryGetChannelHistoryResultRaw(
				results.getString(1),
				results.getTimestamp(2),
				results.getString(3)
			);
			result.add(raw);
		}
		results.close();
		return result;
	}

}
